package LPU;
import weka.core.FastVector;
import weka.core.Instances;
import weka.classifiers.Classifier;
import weka.classifiers.Evaluation;
import weka.classifiers.bayes.BayesNet;
import weka.classifiers.evaluation.EvaluationUtils;
import weka.classifiers.evaluation.NominalPrediction;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;

public class wekaLPU {
	private String trainDataFile;
	private String testDataFile;
	private String resultFile;
	
	public wekaLPU(String train, String test, String result){
		this.trainDataFile = train;
		this.testDataFile = test;
		this.resultFile = result;
	}
	
	public static void main(String[] args){
		wekaLPU runWeka = new wekaLPU("output/LPU/lpu_train.arff", "output/LPU/lpu_test.arff", "output/weka/result");
		runWeka.wekaNBnetIterator();
	}
	public void wekaNBnetIterator(){
		try {
			/**get train & test data
			 */
			Instances trainData = new Instances(
			        										new BufferedReader(
			        												new FileReader(trainDataFile)));
			trainData.setClassIndex(0);//change from numAttributes()-1 to 0
			Instances testData = new Instances(
															new BufferedReader(
																	new FileReader(testDataFile)));
			testData.setClassIndex(0);
			
			/**Option handling
			 */
			String param = 
					"weka.classifiers.bayes.BayesNet -D -Q weka.classifiers.bayes.net.search.local.K2 -- -P 1 -S BAYES -E weka.classifiers.bayes.net.estimate.SimpleEstimator -- -A 0.5";
		
			/**build classifier
			 */
			BayesNet cls = new BayesNet();      //new instance of bayes net
			//cls.setOptions(weka.core.Utils.splitOptions(param));      // set the options
			cls.buildClassifier(trainData);
			
			/**evaluate classifier and print some statistics
			 */
			EvaluationUtils eval = new EvaluationUtils();
			FastVector results = eval.getTestPredictions(cls, testData);
			FileWriter fw = new FileWriter(resultFile);
			for(int i = 0; i < results.size(); i++){
				NominalPrediction curPredict = (NominalPrediction)results.elementAt(i);
				fw.write(curPredict.actual() + " " + curPredict.predicted() + "\n");
			}
			fw.close();
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
}
